<template>
	<div class="interface-call-input-container">
		<!-- 请求参数分支 -->
		<p class="label-text">
			<span class="required">*</span>
			<span class="response-text">请求参数</span>
		</p>
		<!-- <template> -->
		<div class="answer-branch" ref="answerBranch">
			<div v-for="(item, index) in requestBody" :key="index" class="formItemContent">
				<el-form-item :prop="`${prop}.${index}.fieldName`" :rules="rules.fieldName">
					<el-input v-model="item.fieldName" placeholder="" style="width: 245px" @change="onChangeParameters">
						<i slot="prefix" class="fieldName-text">字段名：</i>
					</el-input>
				</el-form-item>

				<el-form-item :prop="`${prop}.${index}.parameterName`" :rules="rules.parameterName">
					<!-- :popper-append-to-body="false" -->
					<el-select
						:value="item.parameterName"
						placeholder=""
						:disabled="showDetail"
						@change="onChangeParameters"
						:popper-append-to-body="false"
						popper-class="var-scroll-select"
						style="width: 245px"
						@focus="onFocus"
						@blur="onBlur"
					>
						<el-tabs v-model="activeName" @tab-click="handleClick" class="interface-call-customer-text">
							<el-tab-pane label="客户信息" name="customer" class="customer-box">
								<div class="interface-call-role-box">
									<p class="role-text">角色：</p>
									<el-tag v-for="item in roleData" :key="item.id" class="role-tag" :class="{ activeTag: activeTag === item.id }" @click="checkRole(item.id)">{{ item.name }}</el-tag>
								</div>
								<el-option v-for="v in getVariablesByRole()" :key="v.id" :label="v.id">
									<div class="label" :class="selectId === v.id ? 'select' : ''" @click="onVariable(v, index)">{{ v.name }}</div>
								</el-option>
							</el-tab-pane>
							<el-tab-pane label="业务信息" name="business">
								<el-option v-for="v in businessData" :key="v.id" :label="v.id">
									<div class="label" :class="selectId === v.id ? 'select' : ''" @click="onBizVariable(v, index)">{{ v.name }}</div>
								</el-option>
							</el-tab-pane>
						</el-tabs>
						<i slot="prefix" class="fieldName-text">参数名:</i>
					</el-select>
				</el-form-item>

				<i class="el-icon-close delIcon" @click="removeRequestParameters(index)" v-show="!showDetail"></i>
			</div>
		</div>
		<p class="add-condition" @click="addRequestParameters(index)" v-show="!showDetail"> + 添加 </p>
		<p class="add-return-parameters" v-if="requestParametersError">请添加请求参数</p>
		<!-- </template> -->
	</div>
</template>

<script>
import { getAllRole, getBusinessVariables, getVariablesAll } from '@/api/api.js';
export default {
	name: '',
	components: {},
	props: {
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},
		showDetail: {
			type: Boolean,
			default: () => false
		},
		requestParametersError: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		const vaildateFieldName = (rule, value, callback) => {
			console.log('vaildateFieldName', value);
			if (!value) return callback();
			this.requestBody.filter(item => console.log(item.fieldName, 'fieldName'));
			let arr = this.requestBody.filter(item => item.fieldName === value);
			if (arr.length > 1) {
				return callback(new Error('当前存在重复字段名，请检查后重新选择'));
			}
			return callback();
		};
		const vaildateParameterName = (rule, value, callback) => {
			console.log('vaildateParameterName', value);
			// parameterName  勾选了会一直存在校验，主要原因绑定的 :value
			this.requestBody.filter(item => {
				if (item.parameterName === value) {
					return callback();
				}
			});
		};
		return {
			//请求参数
			requestBody: [
				// {
				// 	fieldName: '', // 字段名
				// 	parameterName: '' // 参数名 NULL
				// }
			],
			rules: {
				fieldName: [
					{
						required: true,
						message: '请输入字段名',
						trigger: 'blur'
					},
					{
						validator: vaildateFieldName,
						trigger: ['blur', 'change']
					}
				],
				parameterName: [
					{
						required: true,
						message: '请选择参数名',
						trigger: 'blur'
					},
					{
						validator: vaildateParameterName,
						trigger: ['blur', 'change']
					}
				]
			},
			roleData: [],
			activeName: 'customer',
			activeTag: 1,
			scenId: JSON.parse(sessionStorage.getItem('sceneData'))?.id || this.$route.params.scenId,
			pageData: {
				page: 1,
				pageSize: 100000,
				total: 0
			},
			businessData: [],
			describeList: [],
			parameterName: '',
			selectId: '',
		};
	},

	watch: {
		value(val) {
			console.log('value', val);
			if (val && val.length > 0) {
			let requestParameters = [...val];
			if (requestParameters?.length > 0) {
				this.requestBody = val;
			}
		}
		}
	},

	mounted() {
		console.log(this.value, 'interfaceCallRequestBody:type', this.prop);
		this.initAllRole();
		this.initBusinessData();
		if (this.value && this.value.length > 0) {
			let requestParameters = [...this.requestBody, ...this.value];
			if (requestParameters?.length > 0) {
				this.requestBody = this.value;
			}
		}
	},
	methods: {
		// 添加
		addRequestParameters() {
			this.requestBody.push({ fieldName: '', parameterName: '' });
			console.log(this.requestBody, 'addRequestParameters');
			this.$nextTick(() => {
				// console.log(this.$refs.answerBranch.scrollHeight, 'scrollHeight');
				this.$refs.answerBranch.scrollTo({ top: this.$refs.answerBranch.scrollHeight, behavior: 'smooth' });
			});
			this.$emit('input', this.prop, this.requestBody);
		},
		// 删除判断条件
		removeRequestParameters(index) {
			console.log('removeRequestParameters ', index);
			this.requestBody.splice(index, 1);
			this.$emit('input', this.prop, this.requestBody);
		},
		onChangeParameters() {
			console.log('onChangeParameters', this.form);
			this.$emit('input', this.prop, this.requestBody);
		},
		getVariablesByRole() {
			return this.describeList.filter(item => item.roleId === this.activeTag);
		},
		checkRole(id) {
			this.activeTag = id;
		},
		onVariable(value, index) {
			console.log('onVariable', value, index);
			this.selectId = value.id;
			this.requestBody.map((item, currentIndex) => {
				if (index === currentIndex) {
					return (item.parameterName = `{{客户信息_${value.roleName}_${value.name}_${value.id}}}`);
				}
			});
		},
		onBizVariable(value, index) {
			console.log(index, 'onBizVariable', value);
			this.selectId = value.id;
			this.requestBody.map((item, currentIndex) => {
				if (index === currentIndex) {
					return (item.parameterName = `{{业务信息_${value.name}_${value.id}}}`);
				}
			});
		},
		// 初始化所有角色
		initAllRole() {
			getAllRole(this.scenId)
				.then(res => {
					this.roleData = res.data.data;
					this.activeTag = res.data.data[0]?.id;
					// }
					this.getVariablesAll();
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 客户信息变量配置初始化
		initBusinessData() {
			getBusinessVariables({ scenId: this.scenId, page: 1, pageSize: 1000 })
				.then(res => {
					console.log(res.data.data, 'initBusinessData', res);
					if (res.data.code == 200) {
						// .filter(item => item.initMode !== 'api-data')
						this.businessData = res.data.data.data.filter(item => item.initMode !== 'api-data');
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},
		checkRole(id) {
			this.activeTag = id;
		},
		filterCheckCustomer(parameterName) {
			let result = this.describeList.filter(item => item.name === parameterName);
			// console.log(result, 'getSelectVariable:');
			return `客户信息-${result[0].roleName}-${result[0].name}`;
		},
		getVariablesAll() {
			let param = {
				scenId: this.scenId,
				page: 1,
				pageSize: 10000
			};
			getVariablesAll(param)
				.then(res => {
					if (res.data.data && res.data.data.rows) {
						res.data.data.rows.map(item => {
							// 请求参数参数值选择时屏蔽掉获取方式为API获取的变量
							if (item.roleId && item.initMode !== 'api-data') {
								const data = {
									id: item.id,
									name: item.name,
									roleId: item.roleId,
									dataMasking: item.dataMasking,
									params: item.params,
									url: item.url,
									method: item.method,
									linkedKey: item.linkedKey,
									isDefault: item.isDefault,
									key: item.name,
									property: item.type,
									content: '',
									initMode: item.initMode,
									scenId: this.scenId,
									roleName: item.bizscenario_role.name,
									type: item.type
								};
								this.describeList.push(data);
							}
						});
						this.pageData.total = res.data.data.count;
						// filter requestBody
						const list = res.data.data.rows.filter(item => item.initMode !== 'api-data');
						this.filterRequestBody(list)
					} else {
						console.warn('get variable list error ', res.data);
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},
		filterRequestBody(list) {
			// this.requestBody = this.requestBody.filter(item => list.find(item2 => item2.name === item.parameterName.split('_')[2] || item2.name === item.parameterName.split('_')[1]));
			// 只清参数名的数据
			this.requestBody?.map(item => {
				if (!list.find(item2 => item2.name === item.parameterName.split('_')[2] || item2.name === item.parameterName.split('_')[1])) {
					item.parameterName = "";
				}
			})
		},
		onFocus() {
			// disable scroll 
			const template = document.querySelector('div.ai-template-view-wrapper div')
			if (template) {
				template.style.overflow = 'hidden'
			}
		},
		onBlur() {
			// enable scroll
			const template = document.querySelector('div.ai-template-view-wrapper div')
			if (template) {
				template.style.overflow = 'auto'
			}
		}

	}
};
</script>

<style lang="less" scoped>
.interface-call-input-container {
	height: fit-content;
	.label-text {
		font-size: 12px;
		font-weight: 400;
		margin-left: 20px;
		.required {
			color: #fc3e3e;
		}
		.response-text {
			color: #666666;
		}
	}
	.response-wrapper {
	}
	.answer-branch {
		background-color: #f9f9f9;
		margin-top: 15px;
		position: relative;
		// padding-left: 10px;
		// padding-top: 10px;
		// padding-bottom: 10px;
		margin-bottom: 16px;
		max-height: 210px;
		overflow-y: auto;
		padding: 10px;
		box-sizing: border-box;
		overflow-x: hidden;
		.delIcon {
			width: 10px;
			height: 10px;
			color: #8d8d92;
			margin-top: 10px;
			font-size: 16px;
			cursor: pointer;
			margin-left: 0px;
		}
		.formItemContent {
			display: flex;
			/deep/ .el-form-item__content {
				margin: 0 !important;
			}
			.fieldName-text {
				font-size: 12px;
				font-weight: 400;
				color: #b8b8b8;
				position: relative;
				left: 5px;
				z-index: 10;
				font-style: normal;
			}
			/deep/.el-input--prefix .el-input__inner {
				padding-left: 50px;
			}
			/deep/.el-form-item__error {
				margin-left: 12px;
			}
		}
	}
	.add-condition {
		width: 80px;
		font-size: 12px;
		font-family: PingFang SC;
		font-weight: 400;
		color: #6384fe;
		cursor: pointer;
		margin-left: 17px;
		// margin-bottom: 5px;
		position: relative;
		bottom: 15px;
	}
	.add-return-parameters {
		color: #f56c6c;
		font-size: 12px;
		// margin-top: -25px;
	}
	/deep/ .el-tabs__nav-wrap::after {
		background-color: none !important;
		position: relative;
		height: 0;
	}
}
</style>
<style lang="less">
.interface-call-input-container .answer-branch .var-scroll-select .el-select__tags {
	width: 100%;
	max-height: 231px;
	overflow-y: auto;
	margin-left: 10px;
}
.interface-call-input-container .answer-branch .var-scroll-select .el-select-dropdown__list {
	width: 641px;
}

.interface-call-customer-text {
	margin-left: 17px;
}

.answer-branch .el-tabs__active-bar {
	background-color: #6384fe !important;
	width: 56px !important;
}
.answer-branch .el-tabs__item {
	font-size: 15px;
	font-family: PingFang SC;
	font-weight: 400;
	color: #b7b7b7 !important;
}
.answer-branch .el-tabs__item.is-active {
	color: #6384fe !important;
}

.answer-branch .el-tabs__nav-wrap::after {
	background-color: none !important;
	position: relative;
	height: 0;
}
</style>
<style>
.interface-call-role-box {
	display: flex;
}
.interface-call-role-box .role-text {
	font-size: 13px;
	font-family: PingFang SC;
	font-weight: 400;
	color: #999999;
}
.interface-call-role-box .role-tag {
	border: 1px solid #c9def8;
	height: 32px;
	background: #ffffff !important;
	border-radius: 4px;
	color: #6784f2 !important;
	margin: 0 7px;
	cursor: pointer;
}
.interface-call-role-box .activeTag {
	border: 1px solid #c9def8;
	height: 32px;
	border-radius: 4px;
	background: #e7f2fe !important;
	color: #5374f2 !important;
	margin: 0 7px;
	cursor: pointer;
}
</style>
